package cn.felord.security.autoconfigure.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author felord.cn
 * @since 2021/8/6 18:10
 */
public abstract class ResponseWriter {
    private static final Logger log = LoggerFactory.getLogger(ResponseWriter.class);
    private final ObjectMapper objectMapper = (new ObjectMapper()).registerModule(new JavaTimeModule());

    public ResponseWriter() {
    }

    public void write(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (response.isCommitted()) {
            log.debug("Response has already been committed");
        } else {
            response.setStatus(200);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
            String resBody = this.objectMapper.writeValueAsString(this.body(request));
            PrintWriter printWriter = response.getWriter();
            printWriter.print(resBody);
            printWriter.flush();
            printWriter.close();
        }
    }

    protected abstract SecurityRest<?> body(HttpServletRequest var1);
}
